import win32event
import win32api
import sys
import winerror
from blue_receive import setup_bluetooth_server, handle_client_connection


def main():
    # Your main code here
    server_sock = setup_bluetooth_server()

    while True:
        client_sock, client_info = server_sock.accept()
        print(f"已接受来自 {client_info} 的连接")
        handle_client_connection(client_sock)


if __name__ == "__main__":
    MUTEX_NAME = "Global\\MyBluetoothServerMutex"  # 更改为您的应用程序名称或其他唯一标识符
    mutex = win32event.CreateMutex(None, False, MUTEX_NAME)
    last_error = win32api.GetLastError()

    if last_error == winerror.ERROR_ALREADY_EXISTS:
        mutex = None
        print("另一个实例已经在运行!")
        sys.exit(1)

    try:
        main()
    finally:
        if mutex:
            win32api.CloseHandle(mutex)
